from redis import StrictRedis
from flask import current_app
import json
from uuid import uuid4
from hashlib import md5


class RedisSession():
    def __init__(self):
        self._conn = StrictRedis()
        self._token = ''

    @property
    def token(self):
        if self._token == '':
            md = md5()
            data = current_app.config['TOKEN_SALT']+str(uuid4())
            data = data.encode()
            md.update(data)
            self._token = md.hexdigest()
        return self._token

    def set(self, key:str, value, expr=None):
        """expr: seconds"""
        if expr is None:
            expr = current_app.config.get('TOKEN_TIMEOUT_VALUE', 7200)
        if not isinstance(value, str):
            value = json.dumps(value)
        self._conn.set(key, value, ex=expr)
        return key

    def get(self, key, dumps=True):
        value = self._conn.get(key)
        if value and dumps:
            try:
                value = value.decode()
                value = json.loads(value)
            except Exception as e:
                print(e)
        return value


r_session = RedisSession()